﻿using Microsoft.AspNet.SignalR.Hosting;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.WarehouseManage;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BasicsDatumServer.UnitServer.Dto;
using SmartWMS.Server.Repository;
using SmartWMS.Server.WarehouseManage.CheckServer.Dto;
using SmartWMS.Server.WarehouseManage.InventoryLedgerServer.Dto;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.WarehouseManage.InventoryLedgerServer
{
    /// <summary>
    /// 盘点管理
    /// </summary>
    public class CheckServers: ICheckServers
    {
        private readonly IRepository<Check> _check;
        private readonly IRepository<CheckDetails> _checkDetails;
        private readonly IRepository<Product> _product;
        private readonly SmartWMSContext _smartWMSContext;

        public CheckServers(IRepository<Check> check, IRepository<CheckDetails> checkDetails, IRepository<Product> product, SmartWMSContext smartWMSContext) {
            _check=check;
            _checkDetails=checkDetails;
            _product=product;
            _smartWMSContext=smartWMSContext;
        }
        /// <summary>
        /// 盘点列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<List<CheckDtoPes>>> GetCheckDtoPes(CheckDtoPage dto) {
            try
            {
                // 获取盘点列表
                var plist= await _check.GetAllListAsync();
                var list = plist.MapToList<CheckDtoPes>();
                if (!string.IsNullOrEmpty(dto.CheckCode)) {
                    list= list.Where(t=>t.CheckCode.Contains(dto.CheckCode)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.CreatOrTime)) {
                    list = list.Where(t => t.CreatOrTime>=DateTime.Parse(dto.CreatOrTime)).ToList();
                }
                if (!string.IsNullOrEmpty(dto.CreatOrTimes))
                {
                    list = list.Where(t => t.CreatOrTime <= DateTime.Parse(dto.CreatOrTimes)).ToList();
                }
                if (dto.State > 0) {
                    list = list.Where(t => t.State == dto.State).ToList();
                }
                int totalCount = list.Count();
                int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.size);
                list = list.Skip(dto.page - 1 * dto.size).Take(dto.size).ToList();

                return list != null ? Response<List<CheckDtoPes>>.Ok(list, totalCount, pageCount) : Response<List<CheckDtoPes>>.Fail(new List<CheckDtoPes>());
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DelCheck(CheckDtoPage dto)
        {
            try
            {
                var list = _check.GetListQuery().FirstOrDefault(t => t.CheckCode == dto.CheckCode);
                var plist = await _checkDetails.GetAllListAsync();
                plist = plist.Where(t => t.CheckCode == dto.CheckCode).ToList();

                if (list != null)
                {
                    using (var tran = _smartWMSContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var result = await _check.DeleteByIdAsync(list);
                            if (result > 0)
                            {

                                if (plist != null)
                                {
                                    var i = await _checkDetails.DeleteAsync(plist);
                                    if (i > 0)
                                    {
                                        tran.Commit();
                                        return Response<bool>.Ok(true);
                                    }
                                    else
                                    {
                                        //回滚
                                        tran.Rollback();
                                        return Response<bool>.Fail(false);
                                    }
                                }
                                else
                                {
                                    //回滚
                                    tran.Rollback();
                                    return Response<bool>.Fail(false);
                                }
                            }
                            else
                            {
                                //回滚
                                tran.Rollback();
                                return Response<bool>.Fail(false);
                            }
                        }
                        catch (Exception)
                        {
                            //回滚
                            tran.Rollback();
                            throw;
                        }
                    }

                }
                else
                {
                    return Response<bool>.Fail(false);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 批量删除数据（盘点表盘点明细）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteBatchCheck(List<CheckDtoPage> dto)
        {
            try
            {
                var list = _check.GetListQuery().Where(t => dto.Select(x => x.CheckCode).Contains(t.CheckCode)).ToList();   
                var plist= _checkDetails.GetListQuery().Where(t=>list.Select(x=>x.CheckCode).Contains(t.CheckCode)).ToList();
                
                if (list != null)
                {
                    using (var tran = _smartWMSContext.Database.BeginTransaction()) {
                        try
                        {
                            var result= await _check.DeleteAsync(list);
                            if (result > 0) { 
                                var i= await _checkDetails.DeleteAsync(plist);
                                if (i > 0)
                                {
                                    tran.Commit();
                                    return Response<bool>.Ok(true);
                                }
                                else
                                {
                                    //回滚
                                    tran.Rollback();
                                    return Response<bool>.Fail(false);
                                }
                            }else
                            {
                                //回滚
                                tran.Rollback();
                                return Response<bool>.Fail(false);
                            }
                        }
                        catch (Exception)
                        {
                            //回滚
                            tran.Rollback();
                            throw;
                        }
                    }
                }
                
                else
                {
                    return Response<bool>.Fail(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 添加盘点数据（盘点明细）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddCheck(CheckDtoPes dto) {
            try
            {
                dto.CreatOrTime=DateTime.Now;
                dto.State=1;
                //盘点明细
                var productlist = dto.ProductManagementDto;
                var CheckDetailsLists = productlist.Select(item => new CheckDetails
                {
                    CheckCode = dto.CheckCode,
                    ProductName = item.ProductName,
                    ProductCode = item.ProductCode,
                    Specs = item.Specs,
                    Batch = item.Batch,
                    Location = item.DefaultLocationId.ToString(),
                    Inventory = item.Inventory,
                    CheckNumber= item.CheckNumber,
                }).ToList();
                using (var tran = _smartWMSContext.Database.BeginTransaction()) {
                    try
                    {
                        var result = await _check.InsertAsync(dto.MapTo<Check>());
                        if (result > 0)
                        {
                            var i = await _checkDetails.InsertAsync(CheckDetailsLists);
                            if (i > 0)
                            {
                                //提交
                                tran.Commit();
                                return Response<bool>.Ok(true);
                            }
                            else {
                                //回滚
                                tran.Rollback();
                                return Response<bool>.Fail(false);
                            }

                        }
                        else {
                            //回滚
                            tran.Rollback();
                            return Response<bool>.Fail(false);
                        }
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        throw;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 反填数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public CheckDtoPes ReckCheck(CheckDtoPes dto) {
            try
            {

                var list = _check.GetListQuery().FirstOrDefault(t => t.CheckCode == dto.CheckCode);
                var slist= list.MapTo<CheckDtoPes>();
                var plist = _checkDetails.GetListQuery().Where(t => t.CheckCode == dto.CheckCode).ToList();

                slist.ProductManagementDto = plist.MapToList<ProduDtoPes>();
                return slist;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改单条数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateCheckDetail(ProduDtoPes dto) {
            try
            {
                var result = await _checkDetails.UpdateAsync(dto.MapTo<CheckDetails>());
                return result>0? Response<bool>.Ok(true): Response<bool>.Fail(false);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 批量修改数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateCheck(CheckDtoPes dto) {
            var productlist = dto.ProductManagementDto;
            var CheckDetailsLists = productlist.Select(item => new CheckDetails
            {
                Id= item.Id,
                CheckCode = dto.CheckCode,
                ProductName = item.ProductName,
                ProductCode = item.ProductCode,
                Specs = item.Specs,
                Batch = item.Batch,
                Location = item.Location,
                Inventory = item.Inventory,
                CheckNumber = item.CheckNumber,
            }).ToList();
            using (var tran = _smartWMSContext.Database.BeginTransaction())
            {
                try
                {
                    var result = await _check.UpdateAsync(dto.MapTo<Check>());
                    if (result > 0)
                    {
                        var i = await _checkDetails.UpdateRangeAsync(CheckDetailsLists);
                        if (i > 0)
                        {
                            //提交
                            tran.Commit();
                            return Response<bool>.Ok(true);
                        }
                        else
                        {
                            //回滚
                            tran.Rollback();
                            return Response<bool>.Fail(false);
                        }

                    }
                    else
                    {
                        //回滚
                        tran.Rollback();
                        return Response<bool>.Fail(false);
                    }
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }
        /// <summary>
        /// 订单审核
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateCheckState(CheckDtoPes dto)
        {
            var list = _check.GetListQuery().FirstOrDefault(t => t.CheckCode == dto.CheckCode);
            if (list != null)
            {
                list.State = dto.State;
                list.Reviewer= dto.Reviewer;
                list.Opinion = dto.Opinion;
                list.Audittime = DateTime.Now;
                var result = await _check.UpdateAsync(list);
                return result > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
            }
            else
            {
                return Response<bool>.Fail(false);
            }
        }



    }
}
